package ing.lightDogs.turetJson;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;

@SuppressWarnings("serial")
public class GetTuret extends HttpServlet {
	Geohash geohash = new Geohash();
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	           throws IOException
	    {
	    	resp.setContentType("application/json");
	        PrintWriter out = resp.getWriter();
	        
	        try{
	        	Double latitude = Double.parseDouble(req.getParameter("latitude"));
	        	Double longitude = Double.parseDouble(req.getParameter("longitude"));
	        	Double distance = Double.parseDouble(req.getParameter("distance"));
	        	if (distance==null) distance = 0.1;
	        	
	        	int angle=-45;
	        	String geohashpoint2=geohash.shiftGeopoint(latitude,longitude,distance,angle);
	        	double coor[]=geohash.decode(geohashpoint2);
	        	resp.getWriter().println("NW " + geohashpoint2+" "+coor[0]+" "+coor[1]);
	        	double lat1=coor[0];
	        	double lon1=coor[1];
	        	
	        	angle=135;
	        	String geohashpoint=geohash.shiftGeopoint(latitude,longitude,distance,angle);
	        	coor=geohash.decode(geohashpoint);
	        	resp.getWriter().println("SE "+geohashpoint+" "+coor[0]+" "+coor[1]);
	        	double lat2=coor[0];
	        	double lon2=coor[1];
	        	
//	        	angle=0;
//	        	distance=(double) 0; 
//	        	String geohashpoint3=geohash.shiftGeopoint(latitude,longitude,distance,angle);
//	        	coor=geohash.decode(geohashpoint3);
//	        	resp.getWriter().println(geohashpoint3+" "+coor[0]+" "+coor[1]);
	        	
	        	
	        EntityManager em = EMFService.get().createEntityManager();
	        List<Turet> turetsQueried = null;
	        try {
//	        	 Query q = em.createQuery("SELECT t from Turet t where t.geohash BETWEEN :gh1 and :gh2");
//	        	 Query q = em.createQuery("SELECT t from Turet t where t.distance > (SQRT((t.latitude - latitude)^2 + (t.longitude - longitude)^2))");
	        	 Query q = em.createQuery("SELECT t from Turet t where t.latitude>(:lat2) and t.latitude<(:lat1) ");
//	        	 Query q = em.createQuery("SELECT t from Turet t where t.latitude IN (SELECT t1.latitude from Turet t1 where t1.latitude<(:lat+10) and t1.latitude>(:lat-10))");
//				 Query q = em.createQuery("SELECT t from Turet t where t.latitude<(:lat+10) and t.latitude>(:lat-10) and t.longitude<(:lon+10) and t.longitude>(:lon-10) order by (abs(t.latitude - :lat) + abs(t.longitude - :lon))");
				 q.setParameter("gh1", geohashpoint);
				 q.setParameter("gh2", geohashpoint2);				 
				 q.setParameter("lon", longitude);
				 q.setParameter("lat1", lat1);
				 q.setParameter("lat2", lat2);
				 q.setParameter("lon1", lon1);
				 q.setParameter("lon2", lon2);
				 q.setParameter("distance", distance);
//				 q.setMaxResults(10);
				 turetsQueried = new ArrayList(q.getResultList());
//				 for (Turet t : turetsQueried) {
//					 if ((t.getLongitude() > lon2)||(t.getLongitude() < lon1)){
//						 turetsQueried.remove(t);
//					 }
//				 }						
			} finally {
				 em.close();
			}
	        if (turetsQueried.isEmpty()) {
	        	resp.getWriter().println("no turets queried.");
	        } else {
	        	int index=1;
	        	String jsonString= "";
	        	jsonString+="{\"turets\":";
	        	jsonString+=" [";
	        	for (Turet turet : turetsQueried) {
	        		
//	        		if ((turet.getLongitude() < lon2)&&(turet.getLongitude() > lon1)){
					if (geohash.checkdistance(turet.getLatitude(),turet.getLongitude(), latitude, longitude,distance)) {
						if ((index != turetsQueried.size())&&(index != 1)){
							jsonString+=",";
						}
						jsonString+=turet.toJson();
						index++;
					}
	        			
	        	}
	        	jsonString+=" ]";
	        	jsonString+="}";
	        	
	        	out.println(jsonString);
	        	//TODO adjust xml descrpition field img "
	        	JSONObject jsonObject=new JSONObject(jsonString);
	        	//out.println(jsonObject.toString());
	        }
	        }
	        catch (NumberFormatException nfe) {
				resp.getWriter()
						.println(
								"Wrong number format " +nfe);
			} catch (NullPointerException npe) {
				resp.getWriter()
						.println(
								"Missing parameters " +npe);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        
	    }
}
